package com.qy.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.qy.service.WxService;
import com.qy.utils.HttpUtils;

@WebServlet("/getUserInfo")
public class GetUserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.用户同意授权，获取code
		String code = request.getParameter("code");
		//2.通过code获取网页授权的access_token
		String url = " https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		url = url.replace("APPID", WxService.APPID).replace("CODE", code).replace("SECRET", WxService.APPSECRET);
		String string = HttpUtils.sendGet(url);
		JSONObject jsonObject = JSONObject.parseObject(string);
		String accessToken = jsonObject.getString("access_token");
		String openid = jsonObject.getString("openid");
		//3.刷新access_token（如果需要）
		//4.通过token获取用户信息
		String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		getUserInfoUrl = getUserInfoUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
		String userInfoJsonStr = HttpUtils.sendGet(getUserInfoUrl);
		System.out.println(userInfoJsonStr);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
